package com.carcenter.personnel.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.carcenter.common.result.Result;
import com.carcenter.common.result.enums.impl.BusinessCode;
import com.carcenter.personnel.entity.RolePermissions;
import com.carcenter.personnel.service.IRolePermissionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author car
 * @since 2025-07-16
 */
@RestController
@RequestMapping("/role-permissions")
public class RolePermissionsController {

    @Autowired
    IRolePermissionsService rolePermissionsService;

    @PutMapping("/modifyPermissionsWithRoleId/{roleId}")
    @Transactional(rollbackFor = Exception.class)
    public Result modifyPermissionsWithRoleId(@PathVariable Integer roleId, @RequestBody List<Integer> permissionIds) {
        LambdaQueryWrapper<RolePermissions> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RolePermissions::getRoleId, roleId);
        rolePermissionsService.remove(wrapper);
        if (permissionIds != null && permissionIds.size() > 0) {
            for (Integer permissionId : permissionIds) {
                RolePermissions rolePermissions = new RolePermissions();
                rolePermissions.setRoleId(roleId);
                rolePermissions.setPermissionId(permissionId);
                rolePermissionsService.save(rolePermissions);
            }
        }

        return Result.ok(BusinessCode.MODIFY_SUCCESS.getMessage());
    }
}
